package com.yejq.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.Socket;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yejq.Constants;
import com.yejq.util.PropertiesUtils;

/**
 * shell
 * @author yejq
 */
public class Bingbingdb{

	private static Logger logger = LoggerFactory.getLogger(Bingbingdb.class);

	public Bingbingdb() {
	}
	
	public static void main(String[] args) {
		Socket socket = null;
		BufferedReader commondReader = null;
		OutputStreamWriter writer = null;
		Reader reader = null;
		try {
			socket = new Socket("localhost", PropertiesUtils.getInt(Constants.KEY_PORT));
			logger.info("connected to bingbingdb.");
			System.out.print(">");
			commondReader = new BufferedReader(new InputStreamReader(System.in));
			while(true){
				String commond = commondReader.readLine();

				logger.info("commond:{}", commond);
				writer = new OutputStreamWriter(socket.getOutputStream());
				writer.write(commond);
				writer.write(Constants.EOF);
				writer.flush();

				reader = new InputStreamReader(socket.getInputStream());
				char chars[] = new char[64];
				int len;
				StringBuilder result = new StringBuilder();
				String temp;
				int index;
				while ((len = reader.read(chars)) != -1) {
					temp = new String(chars, 0, len);
					if ((index = temp.indexOf(Constants.EOF)) != -1) {// 遇到eof时就结束接收
						result.append(temp.substring(0, index));
						break;
					}
					result.append(temp);
				}
				logger.info(result.toString());

				if (Constants.QUIT.equalsIgnoreCase(commond)) {
					break;
				}
				System.out.print(">");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (commondReader != null) {
				try {
					commondReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
